package org.mnj07.jms.topic;

import javax.annotation.Resource;
import javax.jms.*;

public class AsyncListener implements MessageListener
{
  @Resource(lookup = "jms/javaee6/ConnectionFactory")
  private static ConnectionFactory connectionFactory;
  @Resource(lookup = "jms/javaee6/Topic")
  private static Topic topic;

  public static void main(String[] args) {

      System.out.println("\nStarting listener....");

      try {
          // Creates the needed artifacts to connect to the queue
          Connection connection = connectionFactory.createConnection();
          Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
          MessageConsumer consumer = session.createConsumer(topic);
          consumer.setMessageListener(new AsyncListener());
          connection.start();

      } catch (Exception e) {
          e.printStackTrace();
      }
  }

  public void onMessage(Message message) {
      try {
          System.out.println("Message received: " + ((TextMessage) message).getText());
      } catch (JMSException e) {
          e.printStackTrace();
      }
  }
}
